package com.care.controller.admin.sys;

import com.alibaba.fastjson.JSONObject;
import com.care.author.AuthRequired;
import com.care.controller.vo.JsonResult;
import com.care.dao.mapper.AdminMapper;
import com.care.dao.mapper.ForumCommentMapper;
import com.care.dao.mapper.ForumMapper;
import com.care.dao.mapper.UserMapper;
import com.care.dao.model.Admin;
import com.care.dao.model.Forum;
import com.care.dao.model.ForumComment;
import com.care.utils.page.PageView;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 后台管理api：帖子与帖子评论管理
 * @author xujinnan
 *
 */
@RequestMapping("/admin/forum")
@RestController
public class AdminForumApiController {

    @Autowired
    private ForumMapper forumMapper;
    @Autowired
    private ForumCommentMapper forumCommentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;

    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //注册自定义的编辑器
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 帖子列表
     * @param session
     * @param page
     * @param kw
     * @return
     */
    @RequestMapping("list")
    public JsonResult forumList(HttpSession session, PageView<Forum> page, String kw) {
        JsonResult result = new JsonResult(true, "0", "查询成功");
        Example example = new Example(Forum.class);
        Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(kw)){
            criteria.andLike("title", "%"+kw+"%");
        }
//        criteria.andEqualTo("status", 1);
        example.orderBy("publishTime").desc();
        List<Forum> list = forumMapper.selectByExampleAndRowBounds(example, new RowBounds(page.getFirstResult(), page.getMaxresult()));
        for(Forum forum:list){
            if(forum.getUserId()!=null){
                forum.setUser(userMapper.selectByPrimaryKey(forum.getUserId()));
            }
            if(forum.getAdminId()!=null){
                forum.setAdmin(adminMapper.selectByPrimaryKey(forum.getAdminId()));
            }
        }
        page.setRecords(list);
        page.setTotalrecord(forumMapper.selectCountByExample(example));
        result.setData(page);
        return result;
    }

    @RequestMapping("detail")
    public JsonResult forumDetail(Integer forumId) {
        JsonResult result = new JsonResult(true, "0", "查询成功");
        Forum forum = forumMapper.selectByPrimaryKey(forumId);
        forum.setUser(userMapper.selectByPrimaryKey(forum.getUserId()));
        forum.setAdmin(adminMapper.selectByPrimaryKey(forum.getAdminId()));
        JSONObject jo = new JSONObject();
        jo.put("forum", forum);
        result.setData(jo);
        Example example = new Example(ForumComment.class);
        Criteria criteria = example.createCriteria();
        criteria.andEqualTo("forumId",forumId);
        example.orderBy("publishTime").desc();
        List<ForumComment> forumCommentList = forumCommentMapper.selectByExample(example);
        for(ForumComment fc:forumCommentList){
            if(fc.getUserId()!=null){
                fc.setUser(userMapper.selectByPrimaryKey(fc.getUserId()));
            }
            if(fc.getAdminId()!=null){
                Admin currAdmin = adminMapper.selectByPrimaryKey(fc.getAdminId());
                fc.setAdmin(currAdmin);
            }
        }
        jo.put("comments", forumCommentList);
        return result;
    }

    @RequestMapping("delete")
    public JsonResult deleteForum(Integer forumId) {
        JsonResult result = new JsonResult(true, "0", "删除成功");
        forumMapper.deleteByPrimaryKey(forumId);
        return result;
    }

    @RequestMapping("comment/delete")
    public JsonResult deleteComment(Integer commentId) {
        JsonResult result = new JsonResult(true, "0", "删除成功");
        forumCommentMapper.deleteByPrimaryKey(commentId);
        return result;
    }

    /**
     * 社区管理员发帖子
     * @param request
     * @param forum
     * @return
     */
    @RequestMapping("save")
    @AuthRequired
    public JsonResult saveForum(HttpServletRequest request, Forum forum) {
        JsonResult result = new JsonResult(true, "0", "保存成功");
        Admin mer = (Admin)request.getAttribute("loginAdmin");
        try {
            forum.setPublishTime(new Date());
            forum.setAdminId(mer.getAdminId());
            forumMapper.insertSelective(forum);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("保存失败");
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 发表评论
     * @param request
     * @param comment
     * @return
     */
    @RequestMapping("comment/save")
    @AuthRequired
    public JsonResult saveForumComment(HttpServletRequest request, ForumComment comment) {
        JsonResult result = new JsonResult(true, "0", "保存成功");
        Admin mer = (Admin)request.getAttribute("loginAdmin");
        try {
            comment.setPublishTime(new Date());
            comment.setAdminId(mer.getAdminId());
            forumCommentMapper.insertSelective(comment);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("保存失败");
            result.setSuccess(false);
        }
        return result;
    }
}
